/**
 * 商店管理相关API接口
 */

import { request, mockSuccess, mockError } from '@/utils/request'

/**
 * 获取商店账户信息
 * @returns {Promise} 账户信息
 */
export const getStoreAccount = () => {
  return request.get('/store/account', {}, {}, () => {
    return mockSuccess({
      id: 1,
      storeName: '测试商店',
      storeCode: 'STORE001',
      ownerName: '张三',
      ownerPhone: '13800000001',
      ownerIdCard: '110101199001010001',
      businessLicense: '91110000000000001X',
      address: '北京市朝阳区测试街道123号',
      description: '这是一个测试商店的描述信息',
      status: 1,
      statusName: '正常营业',
      balance: 15680.50,
      frozenAmount: 0,
      totalIncome: 156800.00,
      totalExpense: 45600.00,
      memberCount: 1250,
      productCount: 89,
      orderCount: 3456,
      rating: 4.8,
      reviewCount: 567,
      createTime: '2023-01-15T10:00:00.000Z',
      updateTime: new Date().toISOString(),
      businessHours: {
        monday: { open: '09:00', close: '21:00', closed: false },
        tuesday: { open: '09:00', close: '21:00', closed: false },
        wednesday: { open: '09:00', close: '21:00', closed: false },
        thursday: { open: '09:00', close: '21:00', closed: false },
        friday: { open: '09:00', close: '21:00', closed: false },
        saturday: { open: '09:00', close: '22:00', closed: false },
        sunday: { open: '10:00', close: '20:00', closed: false }
      },
      images: [
        '/images/store1.jpg',
        '/images/store2.jpg',
        '/images/store3.jpg'
      ],
      certificates: [
        { name: '营业执照', url: '/files/business-license.pdf', uploadTime: '2023-01-15T10:00:00.000Z' },
        { name: '食品经营许可证', url: '/files/food-license.pdf', uploadTime: '2023-01-15T10:30:00.000Z' }
      ]
    })
  })
}

/**
 * 更新商店账户信息
 * @param {object} data - 更新数据
 * @returns {Promise} 更新结果
 */
export const updateStoreAccount = (data) => {
  return request.put('/store/account', data, {}, (params) => {
    return mockSuccess({
      ...params,
      updateTime: new Date().toISOString()
    }, '商店信息更新成功')
  })
}

/**
 * 获取商店申请流程
 * @returns {Promise} 申请流程
 */
export const getStoreApplicationProcess = () => {
  return request.get('/store/application/process', {}, {}, () => {
    return mockSuccess([
      {
        step: 1,
        title: '提交申请',
        description: '填写基本信息并提交申请',
        status: 'completed',
        completedTime: '2023-01-10T10:00:00.000Z'
      },
      {
        step: 2,
        title: '资料审核',
        description: '平台审核提交的资料',
        status: 'completed',
        completedTime: '2023-01-12T14:00:00.000Z'
      },
      {
        step: 3,
        title: '实地考察',
        description: '工作人员实地考察商店',
        status: 'completed',
        completedTime: '2023-01-14T16:00:00.000Z'
      },
      {
        step: 4,
        title: '签署协议',
        description: '签署入驻协议',
        status: 'completed',
        completedTime: '2023-01-15T10:00:00.000Z'
      },
      {
        step: 5,
        title: '开通服务',
        description: '开通商店服务',
        status: 'completed',
        completedTime: '2023-01-15T11:00:00.000Z'
      }
    ])
  })
}

/**
 * 提交商店申请
 * @param {object} data - 申请数据
 * @returns {Promise} 申请结果
 */
export const submitStoreApplication = (data) => {
  return request.post('/store/application', data, {}, (params) => {
    const { storeName, ownerName, ownerPhone, businessLicense } = params
    
    if (!storeName || !ownerName || !ownerPhone || !businessLicense) {
      return mockError('请填写完整的申请信息', 400)
    }
    
    return mockSuccess({
      id: Date.now(),
      applicationNo: `APP${new Date().getFullYear()}${String(Date.now()).slice(-6)}`,
      ...params,
      status: 1,
      statusName: '待审核',
      submitTime: new Date().toISOString()
    }, '商店申请提交成功')
  })
}

/**
 * 获取部门管理列表
 * @param {object} params - 查询参数
 * @returns {Promise} 部门列表
 */
export const getDepartmentList = (params = {}) => {
  return request.get('/store/departments', params, {}, (queryParams) => {
    const { page = 1, pageSize = 20, keyword = '' } = queryParams
    
    const mockDepartments = Array.from({ length: 25 }, (_, index) => ({
      id: index + 1,
      name: `部门${index + 1}`,
      code: `DEPT${String(index + 1).padStart(3, '0')}`,
      parentId: index > 10 ? Math.floor(Math.random() * 10) + 1 : null,
      parentName: index > 10 ? `部门${Math.floor(Math.random() * 10) + 1}` : null,
      level: index > 10 ? 2 : 1,
      description: `这是部门${index + 1}的描述信息`,
      managerName: `部门经理${index + 1}`,
      managerPhone: `138${String(index + 1).padStart(8, '0')}`,
      employeeCount: Math.floor(Math.random() * 20) + 5,
      status: Math.random() > 0.1 ? 1 : 0,
      statusName: Math.random() > 0.1 ? '启用' : '禁用',
      sort: index + 1,
      createTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
      updateTime: new Date().toISOString()
    }))
    
    // 过滤数据
    let filteredDepartments = mockDepartments
    if (keyword) {
      filteredDepartments = mockDepartments.filter(dept => 
        dept.name.includes(keyword) || 
        dept.code.includes(keyword) ||
        dept.managerName.includes(keyword)
      )
    }
    
    // 分页
    const total = filteredDepartments.length
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const list = filteredDepartments.slice(start, end)
    
    return mockSuccess({
      list,
      total,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: Math.ceil(total / pageSize)
    })
  })
}

/**
 * 获取部门详情
 * @param {number} id - 部门ID
 * @returns {Promise} 部门详情
 */
export const getDepartmentDetail = (id) => {
  return request.get(`/store/departments/${id}`, {}, {}, () => {
    return mockSuccess({
      id: Number(id),
      name: `部门${id}`,
      code: `DEPT${String(id).padStart(3, '0')}`,
      parentId: id > 10 ? Math.floor(Math.random() * 10) + 1 : null,
      parentName: id > 10 ? `部门${Math.floor(Math.random() * 10) + 1}` : null,
      level: id > 10 ? 2 : 1,
      description: `这是部门${id}的详细描述信息`,
      managerName: `部门经理${id}`,
      managerPhone: `138${String(id).padStart(8, '0')}`,
      managerEmail: `manager${id}@example.com`,
      employeeCount: Math.floor(Math.random() * 20) + 5,
      status: 1,
      statusName: '启用',
      sort: Number(id),
      address: '北京市朝阳区测试街道123号',
      createTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
      updateTime: new Date().toISOString(),
      children: id <= 10 ? Array.from({ length: Math.floor(Math.random() * 3) + 1 }, (_, index) => ({
        id: Number(id) * 10 + index + 1,
        name: `子部门${index + 1}`,
        code: `DEPT${String(Number(id) * 10 + index + 1).padStart(3, '0')}`,
        employeeCount: Math.floor(Math.random() * 10) + 2
      })) : []
    })
  })
}

/**
 * 创建部门
 * @param {object} data - 部门数据
 * @returns {Promise} 创建结果
 */
export const createDepartment = (data) => {
  return request.post('/store/departments', data, {}, (params) => {
    const { name, code } = params
    
    if (!name || !code) {
      return mockError('请填写部门名称和编码', 400)
    }
    
    return mockSuccess({
      id: Date.now(),
      ...params,
      employeeCount: 0,
      status: 1,
      statusName: '启用',
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    }, '部门创建成功')
  })
}

/**
 * 更新部门
 * @param {number} id - 部门ID
 * @param {object} data - 更新数据
 * @returns {Promise} 更新结果
 */
export const updateDepartment = (id, data) => {
  return request.put(`/store/departments/${id}`, data, {}, (params) => {
    return mockSuccess({
      id: Number(id),
      ...params,
      updateTime: new Date().toISOString()
    }, '部门更新成功')
  })
}

/**
 * 删除部门
 * @param {number} id - 部门ID
 * @returns {Promise} 删除结果
 */
export const deleteDepartment = (id) => {
  return request.delete(`/store/departments/${id}`, {}, () => {
    return mockSuccess(null, '部门删除成功')
  })
}

/**
 * 获取员工管理列表
 * @param {object} params - 查询参数
 * @returns {Promise} 员工列表
 */
export const getEmployeeList = (params = {}) => {
  return request.get('/store/employees', params, {}, (queryParams) => {
    const { page = 1, pageSize = 20, keyword = '', departmentId, status } = queryParams
    
    const mockEmployees = Array.from({ length: 80 }, (_, index) => ({
      id: index + 1,
      employeeNo: `EMP${String(index + 1).padStart(4, '0')}`,
      name: `员工${index + 1}`,
      phone: `138${String(index + 1).padStart(8, '0')}`,
      email: `employee${index + 1}@example.com`,
      idCard: `110101199001010${String(index + 1).padStart(3, '0')}`,
      gender: Math.random() > 0.5 ? 1 : 2,
      genderName: Math.random() > 0.5 ? '男' : '女',
      age: Math.floor(Math.random() * 30) + 25,
      departmentId: Math.floor(Math.random() * 10) + 1,
      departmentName: `部门${Math.floor(Math.random() * 10) + 1}`,
      position: ['店长', '副店长', '收银员', '导购员', '仓管员'][Math.floor(Math.random() * 5)],
      salary: Math.floor(Math.random() * 5000) + 3000,
      hireDate: new Date(Date.now() - Math.random() * 1000 * 24 * 60 * 60 * 1000).toISOString(),
      status: Math.random() > 0.1 ? 1 : 0,
      statusName: Math.random() > 0.1 ? '在职' : '离职',
      avatar: `/avatars/employee${(index % 10) + 1}.jpg`,
      address: '北京市朝阳区测试街道123号',
      emergencyContact: `紧急联系人${index + 1}`,
      emergencyPhone: `139${String(index + 1).padStart(8, '0')}`,
      createTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
      updateTime: new Date().toISOString()
    }))
    
    // 过滤数据
    let filteredEmployees = mockEmployees
    if (keyword) {
      filteredEmployees = mockEmployees.filter(emp => 
        emp.name.includes(keyword) || 
        emp.employeeNo.includes(keyword) ||
        emp.phone.includes(keyword)
      )
    }
    if (departmentId) {
      filteredEmployees = filteredEmployees.filter(emp => emp.departmentId === Number(departmentId))
    }
    if (status !== undefined) {
      filteredEmployees = filteredEmployees.filter(emp => emp.status === Number(status))
    }
    
    // 分页
    const total = filteredEmployees.length
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const list = filteredEmployees.slice(start, end)
    
    return mockSuccess({
      list,
      total,
      page: Number(page),
      pageSize: Number(pageSize),
      totalPages: Math.ceil(total / pageSize)
    })
  })
}

/**
 * 获取员工详情
 * @param {number} id - 员工ID
 * @returns {Promise} 员工详情
 */
export const getEmployeeDetail = (id) => {
  return request.get(`/store/employees/${id}`, {}, {}, () => {
    return mockSuccess({
      id: Number(id),
      employeeNo: `EMP${String(id).padStart(4, '0')}`,
      name: `员工${id}`,
      phone: `138${String(id).padStart(8, '0')}`,
      email: `employee${id}@example.com`,
      idCard: `110101199001010${String(id).padStart(3, '0')}`,
      gender: 1,
      genderName: '男',
      age: 28,
      departmentId: Math.floor(Math.random() * 10) + 1,
      departmentName: `部门${Math.floor(Math.random() * 10) + 1}`,
      position: '收银员',
      salary: 4500,
      hireDate: '2023-06-15T00:00:00.000Z',
      status: 1,
      statusName: '在职',
      avatar: `/avatars/employee${id}.jpg`,
      address: '北京市朝阳区测试街道123号',
      emergencyContact: `紧急联系人${id}`,
      emergencyPhone: `139${String(id).padStart(8, '0')}`,
      bankAccount: `6222${String(id).padStart(12, '0')}`,
      bankName: '中国银行',
      education: '本科',
      major: '工商管理',
      workExperience: '3年零售行业经验',
      skills: ['收银操作', '客户服务', '商品管理'],
      createTime: '2023-06-15T09:00:00.000Z',
      updateTime: new Date().toISOString(),
      // 工作记录
      workRecords: [
        {
          id: 1,
          date: '2024-01-15',
          checkInTime: '09:00:00',
          checkOutTime: '18:00:00',
          workHours: 8,
          overtime: 0,
          status: 'normal'
        },
        {
          id: 2,
          date: '2024-01-14',
          checkInTime: '09:05:00',
          checkOutTime: '18:30:00',
          workHours: 8.5,
          overtime: 0.5,
          status: 'late'
        }
      ]
    })
  })
}

/**
 * 创建员工
 * @param {object} data - 员工数据
 * @returns {Promise} 创建结果
 */
export const createEmployee = (data) => {
  return request.post('/store/employees', data, {}, (params) => {
    const { name, phone, idCard, departmentId } = params
    
    if (!name || !phone || !idCard || !departmentId) {
      return mockError('请填写完整的员工信息', 400)
    }
    
    return mockSuccess({
      id: Date.now(),
      employeeNo: `EMP${String(Date.now()).slice(-4)}`,
      ...params,
      status: 1,
      statusName: '在职',
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    }, '员工创建成功')
  })
}

/**
 * 更新员工
 * @param {number} id - 员工ID
 * @param {object} data - 更新数据
 * @returns {Promise} 更新结果
 */
export const updateEmployee = (id, data) => {
  return request.put(`/store/employees/${id}`, data, {}, (params) => {
    return mockSuccess({
      id: Number(id),
      ...params,
      updateTime: new Date().toISOString()
    }, '员工信息更新成功')
  })
}

/**
 * 删除员工
 * @param {number} id - 员工ID
 * @returns {Promise} 删除结果
 */
export const deleteEmployee = (id) => {
  return request.delete(`/store/employees/${id}`, {}, () => {
    return mockSuccess(null, '员工删除成功')
  })
}

/**
 * 员工离职
 * @param {number} id - 员工ID
 * @param {object} data - 离职数据
 * @returns {Promise} 离职结果
 */
export const resignEmployee = (id, data) => {
  return request.put(`/store/employees/${id}/resign`, data, {}, () => {
    return mockSuccess({
      id: Number(id),
      status: 0,
      statusName: '离职',
      resignDate: new Date().toISOString()
    }, '员工离职处理成功')
  })
}

/**
 * 获取商店统计数据
 * @param {object} params - 查询参数
 * @returns {Promise} 统计数据
 */
export const getStoreStats = (params = {}) => {
  return request.get('/store/stats', params, {}, () => {
    return mockSuccess({
      overview: {
        totalRevenue: 156800.00,
        monthlyRevenue: 25600.00,
        totalOrders: 3456,
        monthlyOrders: 456,
        totalCustomers: 1250,
        newCustomers: 89,
        totalEmployees: 25,
        activeEmployees: 23
      },
      revenueStats: Array.from({ length: 12 }, (_, index) => ({
        month: index + 1,
        revenue: Math.floor(Math.random() * 30000) + 10000,
        orders: Math.floor(Math.random() * 500) + 200,
        customers: Math.floor(Math.random() * 100) + 50
      })),
      departmentStats: [
        { departmentName: '销售部', employeeCount: 8, revenue: 45600 },
        { departmentName: '客服部', employeeCount: 5, revenue: 0 },
        { departmentName: '仓储部', employeeCount: 6, revenue: 0 },
        { departmentName: '管理部', employeeCount: 6, revenue: 0 }
      ],
      topEmployees: Array.from({ length: 10 }, (_, index) => ({
        id: index + 1,
        name: `员工${index + 1}`,
        position: ['店长', '副店长', '收银员', '导购员'][Math.floor(Math.random() * 4)],
        sales: Math.floor(Math.random() * 50000) + 10000,
        orders: Math.floor(Math.random() * 200) + 50
      }))
    })
  })
}